package com.ruicar.afs.cloud.product.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.product.condition.SchemeLaunchCondition;
import com.ruicar.afs.cloud.product.entity.ProductPlan;
import com.ruicar.afs.cloud.product.entity.SchemeLaunch;
import com.ruicar.afs.cloud.product.enums.FitScope;
import com.ruicar.afs.cloud.product.enums.ProductOnlineStatus;
import com.ruicar.afs.cloud.product.enums.StatusEnum;
import com.ruicar.afs.cloud.product.enums.StatusType;
import com.ruicar.afs.cloud.product.service.ProductPlanService;
import com.ruicar.afs.cloud.product.service.ProductRuleInfoService;
import com.ruicar.afs.cloud.product.service.SchemeLaunchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @author yaorui.zhang
 * @date 2020年5月11日19:40:40
 */
@RestController
@AllArgsConstructor
@RequestMapping("/launchPlan")
@Api(value = "launchPlan", description = "产品投放方案")
public class SchemeLaunchController {

    private final SchemeLaunchService planService;
    private final ProductRuleInfoService ruleInfoService;
    private final ProductPlanService productPlanService;
    private AfsSequenceGenerator afsSequenceGenerator;

    @GetMapping("/info/{id}")
    public IResponse<SchemeLaunch> getLaunchPlanById(@PathVariable String id) {
        return new IResponse<>(planService.getLaunchPlanById(id));
    }

    @PostMapping(value = "/getLaunchPlanListData")
    @ApiOperation(value = "多条件分页获取产品投放方案")
    public IResponse<IPage<SchemeLaunch>> listLaunchPlan(@RequestBody QueryCondition<SchemeLaunchCondition> launchPlanCondition) {
        return IResponse.success(planService.page(new Page(launchPlanCondition.getPageNumber(), launchPlanCondition.getPageSize()), Wrappers.<SchemeLaunch>query().lambda()
                .like(StringUtils.isNotEmpty(launchPlanCondition.getCondition().getName()), SchemeLaunch::getName, launchPlanCondition.getCondition().getName())
                .eq(StringUtils.isNotEmpty(launchPlanCondition.getCondition().getStatus()), SchemeLaunch::getStatus, launchPlanCondition.getCondition().getStatus())
                .like(StringUtils.isNotEmpty(launchPlanCondition.getCondition().getPlanNo()), SchemeLaunch::getPlanNo, launchPlanCondition.getCondition().getPlanNo())
                .orderByDesc(SchemeLaunch::getCreateTime)
        ));
    }

    @RequestMapping(value = "/saveLaunchPlan", method = RequestMethod.POST)
    @ApiOperation(value = "产品投放方案保存")
    public IResponse<SchemeLaunch> saveLaunchPlan(@RequestBody SchemeLaunch launchPlan) {
        //查询是否有相同编号的方案
        SchemeLaunch schemeLaunch = planService.getOne(Wrappers.<SchemeLaunch>query().lambda()
                        .eq(SchemeLaunch::getName, launchPlan.getName())
                , false
        );
        if (schemeLaunch != null && launchPlan.getId() == null) {
            return IResponse.fail("名称重复，请重新填写方案名称！");
        }
        //获取编号
        String planNo = launchPlan.getPlanNo();
        if(StringUtils.isEmpty(planNo)){
            Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_TFFA), StatusType.PRODUCT_NUM_TFFA.toString());
            planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_TFFA) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
            launchPlan.setPlanNo(planNo);
        }
        planService.saveOrUpdate(launchPlan);
        return IResponse.success(launchPlan);
    }

    @RequestMapping(value = "/deletePlan/{id}", method = RequestMethod.DELETE)
    @ApiOperation(value = "通过id删除方案")
    public IResponse<Boolean> deletePlan(@PathVariable String id) {
        SchemeLaunch launchPlan = planService.getById(id);
        if (AfsEnumUtil.key(StatusEnum.YES).equals(launchPlan.getStatus()))
            return new IResponse<Boolean>().setMsg("方案生效不可删除！");

        List<ProductPlan> list = productPlanService.list(Wrappers.<ProductPlan>query().lambda()
                .eq(ProductPlan::getLaunchPlanId, id)
        );
        if (list.size() > 0)
            return IResponse.fail("方案被产品使用不可删除！");

        /**
         * 第一步：删除产品规则信息
         */
        ruleInfoService.delProductRuleInfoList(launchPlan.getId(), AfsEnumUtil.key(FitScope.LAUNCHPLAN));
        /**
         * 第二步：删除方案
         */
        planService.removeById(id);
        return new IResponse<Boolean>().setMsg("删除数据成功!");
    }

    @RequestMapping(value = "/effective", method = RequestMethod.POST)
    @ApiOperation(value = "设置有效")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> effective(@ModelAttribute SchemeLaunchCondition plancondition) {
        for (Long id : plancondition.getIds()) {
            SchemeLaunch plan = planService.getById(id);
            plan.setStatus(AfsEnumUtil.key(StatusEnum.YES));
            planService.updateById(plan);
            ruleInfoService.effectiveRule(plan.getId(), AfsEnumUtil.key(FitScope.LAUNCHPLAN),plan.getName());
        }
        return new IResponse<Boolean>().setData(true).setMsg("批量设置数据有效成功");
    }

    @RequestMapping(value = "/invalid", method = RequestMethod.POST)
    @ApiOperation(value = "设置无效")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<Boolean> invalid(@ModelAttribute SchemeLaunchCondition plancondition) {
        List<ProductPlan> list = productPlanService.list(Wrappers.<ProductPlan>query().lambda()
                .eq(ProductPlan::getStatus, AfsEnumUtil.key(ProductOnlineStatus.GO_ONLINE))
                .in(ProductPlan::getLaunchPlanId, Arrays.asList(plancondition.getIds()))
        );
        if (list.size() > 0) return
                IResponse.fail("方案被上线产品使用不可设置无效！");
        for (Long id : plancondition.getIds()) {
            SchemeLaunch plan = planService.getById(id);
            plan.setStatus(AfsEnumUtil.key(StatusEnum.NO));
            planService.updateById(plan);
            ruleInfoService.invalid(plan.getId(), AfsEnumUtil.key(FitScope.LAUNCHPLAN));
        }
        return new IResponse<Boolean>().setData(true).setMsg("批量设置数据无效成功");
    }

    @RequestMapping(value = "/copyPlan", method = RequestMethod.POST)
    @ApiOperation(value = "产品投放方案复制")
    public IResponse copyPlan(@RequestBody SchemeLaunch launchPlan) {
        //查询是否有相同名称的方案
        SchemeLaunch schemeLaunch = planService.getOne(Wrappers.<SchemeLaunch>query().lambda()
                        .eq(SchemeLaunch::getName, launchPlan.getName())
                , false
        );
        if (schemeLaunch != null) {
            return IResponse.fail("名称重复，请重新填写！");
        }
        //获取编号
        Long seqno = afsSequenceGenerator.genNext(AfsEnumUtil.key(StatusType.PRODUCT_NUM_TFFA), StatusType.PRODUCT_NUM_TFFA.toString());
        String planNo = AfsEnumUtil.key(StatusType.PRODUCT_NUM_TFFA) + DateUtil.year(DateUtil.date()) +StringUtils.leftPad(String.valueOf(seqno), 4, '0');// 编号
        launchPlan.setPlanNo(planNo);
        //原方案ID
        Long schemeLaunchOldId = launchPlan.getId();
        //保存方案
        launchPlan.setId(null);
        launchPlan.setStatus(AfsEnumUtil.key(StatusType.INVALID));
        launchPlan.setCreateBy(null);
        launchPlan.setCreateTime(null);
        planService.save(launchPlan);
        //新方案ID
        String schemeLaunchNewId = launchPlan.getId().toString();
        //复制规则信息
        ruleInfoService.copyRulePlan(schemeLaunchOldId, schemeLaunchNewId, AfsEnumUtil.key(FitScope.LAUNCHPLAN));
        return IResponse.success(launchPlan);
    }

}
